package com.slliver.sentinelservice.controller;


import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.slliver.commonmodel.pay.Pay;
import com.slliver.sentinelservice.service.SentinelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
public class SentinelController {

    @Autowired
    private SentinelService sentinelService;

    /**
     * 创建普通订单
     * http://localhost:7001/sentinel/createPay?userId=1001&productId=1001
     */
    @GetMapping("/sentinel/createPay")
    public Pay createPay(@RequestParam("userId") Long userId, @RequestParam("productId") Long productId){
        return sentinelService.savePay(userId, productId);
    }


    /**
     * 创建秒杀订单
     * http://localhost:7001/sentinel/senkill?userId=1001&productId=1001
     */
    @GetMapping("/sentinel/senkill")
    @SentinelResource(value = "/sentinel/senkillOrder", fallback = "senkillOrderFallback")
    public Pay senkill(@RequestParam(value = "userId", defaultValue = "8888") Long userId,
                       @RequestParam(value = "productId", defaultValue = "9999") Long productId){
        Pay pay = sentinelService.savePay(userId, productId);
        pay.setId(Long.MAX_VALUE);
        return pay;
    }

    /**
     * 热点规则测试
     */
    public Pay senkillOrderFallback(Long userId, Long productId, Throwable e){
        System.out.println("senkillOrderFallback兜底回调被调用");
        Pay pay = new Pay();
        pay.setId(0L);
        pay.setRemark("异常信息:" + e.getMessage());
        return pay;
    }

    /**
     * 模拟读数据库
     * http://localhost:7001/sentinel/readDb
     */
    @GetMapping("/sentinel/readDb")
    public String readDb(){
        log.info("request readDb....");
        return "readDB success ...";
    }

    /**
     * 模拟写数据库操作
     * http://localhost:7001/sentinel/writeDb
     */
    @GetMapping("/sentinel/writeDb")
    public String writeDb(){
        return "writeDb success ...";
    }
}
